<template>
  <div ref="chartContainer" class="price-chart-container"></div>
</template>

<script setup>
import { ref, onMounted, watch, onUnmounted } from 'vue'
import * as echarts from 'echarts'

// 定义props
const props = defineProps({
  chartData: {
    type: Object,
    default: () => ({
      prices: [], // 价格数据
      dates: [], // 日期数据
      buyPoints: [] // 买入点数据，格式为 [{date: '2023-01-01', price: 10.5, amount: 1000}, ...]
    })
  },
  lineColor: {
    type: String,
    default: '#409EFF'
  },
  buyPointColor: {
    type: String,
    default: '#67C23A'
  },
  height: {
    type: String,
    default: '300px'
  },
  showArea: {
    type: Boolean,
    default: true
  },
  smooth: {
    type: Boolean,
    default: true
  },
  title: {
    type: String,
    default: ''
  },
  showXAxis: {
    type: Boolean,
    default: true
  },
  showYAxis: {
    type: Boolean,
    default: true
  }
})

// 图表容器引用
const chartContainer = ref(null)
let chartInstance = null

// 初始化图表
const initChart = () => {
  if (!chartContainer.value || !props.chartData.prices.length) return

  chartInstance = echarts.init(chartContainer.value)

  // 准备买入点数据
  const buyPointData = props.chartData.buyPoints.map(point => {
    // 找到日期对应的索引
    const dateIndex = props.chartData.dates.findIndex(date => date === point.date)
    if (dateIndex === -1) return null
    
    return {
      name: point.date,
      value: [dateIndex, point.price],
      symbolSize: 10,
      itemStyle: {
        color: props.buyPointColor
      },
      buyAmount: point.amount
    }
  }).filter(point => point !== null)

  const option = {
    title: props.title ? {
      text: props.title,
      left: 'center',
      textStyle: {
        fontSize: 14,
        fontWeight: 'normal'
      }
    } : undefined,
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      },
      formatter: function(params) {
        // 处理普通点和买入点的不同显示
        if (params.length > 1) {
          // 有多个系列时
          const pricePoint = params.find(p => p.seriesName === '价格')
          const buyPoint = params.find(p => p.seriesName === '买入点')
          
          let result = `${pricePoint.name}<br/>${pricePoint.seriesName}: ${pricePoint.value[1].toFixed(2)}元`
          
          if (buyPoint) {
            result += `<br/>${buyPoint.seriesName}: ${buyPoint.data.buyAmount} 股`
          }
          
          return result
        } else {
          // 只有一个系列时
          const param = params[0]
          if (param.seriesName === '买入点' && param.data.buyAmount) {
            return `${param.name}<br/>价格: ${param.value[1].toFixed(2)}元<br/>买入: ${param.data.buyAmount} 股`
          } else {
            return `${param.name}<br/>价格: ${param.value[1].toFixed(2)}元`
          }
        }
      }
    },
    grid: {
      left: props.showYAxis ? 50 : 10,
      right: 20,
      top: props.title ? 40 : 10,
      bottom: props.showXAxis ? 30 : 10
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: props.chartData.dates,
      show: props.showXAxis,
      axisLine: {
        lineStyle: {
          color: '#E0E0E0'
        }
      },
      axisLabel: {
        color: '#909399',
        fontSize: 12,
        formatter: function(value) {
          // 简化日期显示，例如 2023-01-01 -> 01-01
          return value.substring(5)
        }
      }
    },
    yAxis: {
      type: 'value',
      show: props.showYAxis,
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      splitLine: {
        lineStyle: {
          color: '#EBEEF5'
        }
      },
      axisLabel: {
        color: '#909399',
        fontSize: 12,
        formatter: function(value) {
          return value.toFixed(2)
        }
      }
    },
    series: [
      {
        name: '价格',
        type: 'line',
        data: props.chartData.prices.map((price, index) => [index, price]),
        smooth: props.smooth,
        showSymbol: false,
        lineStyle: {
          width: 2,
          color: props.lineColor
        },
        areaStyle: props.showArea ? {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: `${props.lineColor}4D` }, // 30% opacity
              { offset: 1, color: `${props.lineColor}1A` }  // 10% opacity
            ]
          }
        } : undefined
      },
      {
        name: '买入点',
        type: 'scatter',
        data: buyPointData,
        symbol: 'circle',
        symbolSize: 8,
        itemStyle: {
          color: props.buyPointColor
        },
        emphasis: {
          scale: true,
          itemStyle: {
            borderColor: '#fff',
            borderWidth: 2,
            shadowBlur: 10,
            shadowColor: 'rgba(0, 0, 0, 0.3)'
          }
        },
        z: 10 // 确保买入点显示在折线上方
      }
    ]
  }

  chartInstance.setOption(option)
}

// 更新图表
const updateChart = () => {
  if (!chartInstance || !props.chartData.prices.length) return

  // 准备买入点数据
  const buyPointData = props.chartData.buyPoints.map(point => {
    // 找到日期对应的索引
    const dateIndex = props.chartData.dates.findIndex(date => date === point.date)
    if (dateIndex === -1) return null
    
    return {
      name: point.date,
      value: [dateIndex, point.price],
      symbolSize: 10,
      itemStyle: {
        color: props.buyPointColor
      },
      buyAmount: point.amount
    }
  }).filter(point => point !== null)

  chartInstance.setOption({
    xAxis: {
      data: props.chartData.dates
    },
    series: [
      {
        name: '价格',
        data: props.chartData.prices.map((price, index) => [index, price]),
        smooth: props.smooth,
        areaStyle: props.showArea ? {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: `${props.lineColor}4D` },
              { offset: 1, color: `${props.lineColor}1A` }
            ]
          }
        } : undefined
      },
      {
        name: '买入点',
        data: buyPointData
      }
    ]
  })
}

// 监听图表数据变化
watch(() => props.chartData, () => {
  if (chartInstance) {
    updateChart()
  } else {
    initChart()
  }
}, { deep: true })

// 监听颜色变化
watch([() => props.lineColor, () => props.buyPointColor], () => {
  if (chartInstance) {
    chartInstance.setOption({
      series: [
        {
          lineStyle: {
            color: props.lineColor
          },
          areaStyle: props.showArea ? {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                { offset: 0, color: `${props.lineColor}4D` },
                { offset: 1, color: `${props.lineColor}1A` }
              ]
            }
          } : undefined
        },
        {
          itemStyle: {
            color: props.buyPointColor
          }
        }
      ]
    })
  }
})

// 监听显示设置变化
watch([() => props.showArea, () => props.smooth, () => props.showXAxis, () => props.showYAxis], () => {
  if (chartInstance) {
    initChart() // 重新初始化图表
  }
})

// 监听窗口大小变化
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize()
  }
}

// 组件挂载时初始化图表
onMounted(() => {
  setTimeout(() => {
    initChart()
    window.addEventListener('resize', handleResize)
  }, 100)
})

// 组件卸载时销毁图表
onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.price-chart-container {
  width: 100%;
  height: v-bind(height);
  border-radius: 4px;
}
</style>